﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Collections;
using System.Text;
using System.Linq;
using System.Xml;

namespace Pavilion
{
    public delegate void NameChangedDelegate(string oldName, string newName);
    public class ResourceItem
    {
        public event NameChangedDelegate NameChanged;

        public string Name { get { return name; } set { SetName(value); } }
        public string ResourcePath { get { return GameEngine.AnimationsDirectory + Name + @"\"; } }

        private string name;
        private Dictionary<Type, IResourceCollection> resourceCollectionDictionary = new Dictionary<Type,IResourceCollection>();

        public ResourceItem(string name)
        {
            this.name = name;
        }

        public void Dispose()
        {
            foreach (IResourceCollection resourceCollection in resourceCollectionDictionary.Values)
                resourceCollection.Dispose();

            resourceCollectionDictionary.Clear();
            resourceCollectionDictionary = null;
        }

        public void LoadFromScript()
        {
            AddResourceCollection(AnimationCollection.LoadFromDirectory(ResourcePath));
            AddResourceCollection(NodeScriptCollection.LoadFromDirectory(ResourcePath, Name));
        }

        public void AddResourceCollection(IResourceCollection resourceCollection)
        {
            if (resourceCollection != null)
                resourceCollectionDictionary.Add(resourceCollection.GetType(), resourceCollection);
        }

        public T ObtainResourceCollection<T>() where T : IResourceCollection
        {
            return (T)resourceCollectionDictionary[typeof(T)];
        }

        public bool ContainResourceCollection<T>() where T : IResourceCollection
        {
            return resourceCollectionDictionary.ContainsKey(typeof(T));
        }

        private void SetName(string value)
        {
            if (name == value)
                return;

            string oldName = name;
            name = value;

            OnNameChanged(oldName, name);
        }

        private void OnNameChanged(string oldName, string newName)
        {
            if (NameChanged != null)
                NameChanged(oldName, newName);
        }
    }
}
